package com.qch.client;

import com.qch.handler.UserClientHandler;
import com.qch.json.JSONSerializer;
import com.qch.json.RpcDecoder;
import com.qch.json.RpcEncoder;
import com.qch.json.RpcRequest;
import com.qch.service.UserService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author qch
 * @Date 2021/1/28
 */
public class RPCConsumer {
    //1.创建线程池对象-》处理自定义事件
    private static ExecutorService executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    //2.声明一个自定义事件处理器 UserClientHandler
    private static UserClientHandler userClientHandler;
    //3.初始化客户端
    public  static void initClient() throws InterruptedException {
        //1.初始化userClientHandler
        userClientHandler=new UserClientHandler();
        //2.创建连接池对象
        EventLoopGroup group=new NioEventLoopGroup();
        //3.创建客户端引导对象
        Bootstrap bootstrap=new Bootstrap();
        //4.配置启动引导对象
        bootstrap.group(group).channel(NioSocketChannel.class)
                //设置请求协议未tcp
                .option(ChannelOption.TCP_NODELAY,true)
                //监听channel并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //pipeline.addFirst(new StringEncoder());

                        pipeline.addFirst( new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        //pipeline.addLast( new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                    }
                });
        bootstrap.connect("127.0.0.1",8999).sync();
    }
    //4.编写方法，使用jdk动态代理创建对象

    /**
     *
     * @param classService 接口类型，根据哪个接口生成子类代理对象
     * @param  “UserService#sayHello#--”
     * @return
     */
/*    public static Object createProxy(Class<?>classService, final String providerParam){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{classService}, new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                      //1)初始化客户端
                        if(userClientHandler==null){
                            initClient();
                        }
                        //2）给UserClienttHandler设置param参数
                        userClientHandler.setParam(providerParam+args[0]);
                        //3)使用线程池，开启一个线程处理call,并返回结果
                        //调call执行写操作，通过get拿值
                        Object result = executorService.submit(userClientHandler).get();
                        return result;
                    }
                });
    }*/
    public static Object createProxy(final Class<?>classService){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{classService}, new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1)初始化客户端
                        if(userClientHandler==null){
                            initClient();
                        }
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(classService.getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(new Class[]{String.class});
                        rpcRequest.setParameters(new String[]{(String) args[0]});
                        //2）给UserClienttHandler设置param参数
                        userClientHandler.setParam(rpcRequest);
                        //3)使用线程池，开启一个线程处理call,并返回结果
                        //调call执行写操作，通过get拿值
                        Object result = executorService.submit(userClientHandler).get();
                        return result;
                    }
                });
    }
}
